<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            :disabled="!checkPermission('EMPLOYEE-IMPORT')"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            :disabled="!checkPermission('EMPLOYEE-EXPORT')"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPermission('EMPLOYEE-ADD')"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="tableList">
          <el-table-column label="序号" sortable="">
            <template slot-scope="scope">
              {{ (page.page - 1) * page.size + (scope.$index + 1) }}</template>
          </el-table-column>
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                class="staffPhoto"
                :src="scope.row.staffPhoto"
                alt=""
                @click="showCodeDialog(scope.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <!-- formatter 用来格式化内容Function(row, column, cellValue, index) -->
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column
            label="
            部门"
            sortable=""
            prop="departmentName"
          />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRoles(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :total="total"
            layout="total,sizes,prev, pager, next,jumper"
            :page-size="page.size"
            :page-sizes="[2, 5, 10, 15]"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>

      <!-- 弹出层 -->
      <add-employee :show-dialog.sync="showDialog" @refresh="getEmployeeList" />
      <!-- 二维码 -->
      <el-dialog :visible="showCode" title="二维码" @close="showCode = false">
        <el-row type="flex" justify="center" align="middle">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assign-role'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from '@/views/employees/components/add-employee'
import { formatDate } from '@/filters'
import QRcode from 'qrcode'
export default {
  components: {
    addEmployee, AssignRole
  },
  data() {
    return {
      userId: '',
      showRoleDialog: false, // 角色弹出层控制
      tableList: [], // 员工列表数据
      page: {
        page: 1,
        size: 2
      },
      total: 0,
      showDialog: false,
      showCode: false // 点击头像弹出弹窗（二维码）
    }
  },
  created() {
    // 获取员工的综合列表数据
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.tableList = rows
      this.total = total
    },
    // pageSize 改变时会触发
    sizeChange(newSize) {
      this.page.size = newSize
      //  刷新 重新请求数据
      this.getEmployeeList(this.page)
    },
    // 页面改变时触发
    currentChange(newpage) {
      this.page.page = newpage
      this.getEmployeeList(this.page)
    },
    // 格式化枚举数据
    formatEmployment(row, column, cellValue, index) {
      let res = '未知'
      // 遍历数据
      EmployeeEnum.hireType.forEach((item) => {
        // 单元格的内容与遍历到的数据的id相同 则将item.value结果赋值给res返回显示在页面单元格上
        if (item.id === cellValue) {
          res = item.value
        }
      })
      // 将结果返回
      return res
    },
    // 利用枚举格式化在职状态
    // formatEnable(row, column, cellValue, index) {
    //   // 遍历数据
    //   const res = EmployeeEnum.stausInfos.find(item => {
    //     // 处理这个有一个小 bug
    //     // 枚举数据提供的 id 字符串
    //     // 传入的是数字, === 全等的判断下, 会无法找到结果
    //     // 强制转换为数字再判断
    //     return Number(item.id) === cellValue
    //   })
    //   // 将结果返回
    //   return res ? res.value : '未知'
    // },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('是否删除该员工信息')
        // 发送删除请求
        await delEmployee(id)
        // 刷新数据
        this.getEmployeeList()
        // 提示信息
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 导出数据
    async exportExcel() {
      // 对数据进行改造
      // 字典
      // 表头对应关系
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // console.log(item);
      // 1. 获取员工数据
      // 请求页码为1, 长度 = total 的数据
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      // console.log(rows)
      const data = rows.map((item) => {
        return this.obj2Array(item, headers)
      })
      // console.log(data)
      // 懒加载（按需引入）
      import('@/vendor/Export2Excel').then((excel) => {
        // console.log(excel)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: data // 具体数据 必填  所需的数据为二维数组
          //   // filename: 'excel-list', // 非必填
          //   // autoWidth: true, // 非必填
          //   // bookType: 'xlsx' // 非必填
        })
      })
    },
    // 数据处理转换的封装
    obj2Array(item, headers) {
      // 定义数组存储所需的数据
      const arr = []
      for (const key in headers) {
        // console.log(key)
        // 根据中文获取所需的英文key
        const newKey = headers[key]
        // 之前直接将数据存在数组即可, 但是发现最终显示的日期不友好
        // 在这里如果发现是正在转换日期的话, 可以添加额外的处理
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          arr.push(formatDate(item[newKey]))
        } else {
          arr.push(item[newKey])
        }
      }
      return arr
    },
    // 展示二维码
    showCodeDialog(imgUrl) {
      if (imgUrl) {
        this.showCode = true
      }
      // 弹窗生产之后再生成二维码
      this.$nextTick(() => {
        // qrcode的用法 QrCode.toCanvas(dom, info)
        QRcode.toCanvas(this.$refs.mycanvas, imgUrl)
      })
    },
    editRoles(id) {
      this.userId = id
      // 调取子组件的函数获取用户角色数据
      this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    // checkPermission(pointsKey) {
    //   if (this.$store.state.user.userInfo.id) {
    //     return this.$store.state.user.userInfo.roles.points.indexOf(pointsKey) > -1
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 80px;
  height: 80px;
  object-fit: cover;
}
</style>
